import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {adSystemApiUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';

@Component({
  selector: 'app-clear-cache',
  templateUrl: './clear-cache.component.html',
  styleUrls: ['./clear-cache.component.scss']
})
export class ClearCacheComponent implements OnInit {

  applet_uuid;
  applet_name;
  cache_name = [];

  type: string;
  message: string;
  isShow = false;

  constructor(private route: ActivatedRoute,
                private router: Router,
                private httpService: HttpService) { }

  ngOnInit() {
    this.applet_uuid = this.route.snapshot.queryParams['applet_uuid'];
    this.applet_name = this.route.snapshot.queryParams['name'];
  }

  checkedCache(name,order) {
    if (!this.cache_name.length) {
      let data = {name: name, order: order};
      this.cache_name.push(data);
    } else {
      let isExist = false;
      this.cache_name.every((val, idx, array) => {
        if (val.order == order) {
          isExist = true;
          this.cache_name.splice(idx, 1);
          return false;
        }
        return true;
      });
      if (!isExist) {
        let data = {name: name, order: order};
        this.cache_name.push(data);
      }
    }
  }

  clearCache() {
    let cache = [];
    this.cache_name.every((val, idx, array) => {
      cache.push(val.name);
      return true;
    });
    const data = {cache_name: JSON.stringify(cache), applet_uuid: this.applet_uuid};
    const url = `${adSystemApiUrl}/v1/admin/site_setting/cache_clear`;
    return this.httpService.httpPostAuth(url, data).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '缓存清除成功';
          this.isShow = true;
          // this.router.navigate(['admin/program-manage/program-list']);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    )
  }
}
